package com.qqt.csr.common.session;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * 
 * @ClassName: BaseThreadLocal
 * @Description: 线程私有本地变量方法封装
 *
 */
public class BaseThreadLocal {

	public static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<Map<String, Object>>();

	public static void set(String key, Object value) {
		Map<String, Object> map = threadLocal.get();
		if (map == null) {
			map = new HashMap<String, Object>();
			threadLocal.set(map);
		}
		map.put(key, value);
	}

	public static void set(Object obj) {
		Map<String, Object> mapValue = BeanUtil.beanToMap(obj);
		Map<String, Object> localMap = threadLocal.get();
		if (localMap == null) {
			localMap = new HashMap<String, Object>();
			threadLocal.set(localMap);
		}
		if (mapValue != null) {
			localMap.putAll(mapValue);
		}

	}

	public static Object get(String key) {
		Map<String, Object> localMap = threadLocal.get();
		if (localMap == null) {
			localMap = new HashMap<String, Object>();
			threadLocal.set(localMap);
		}
		return localMap.get(key);
	}

	public static String getString(String key) {

		return StrUtil.toString(get(key));
	}

	@SuppressWarnings("unchecked")
	public static <T> T getObject(String key, Class<T> t) {
		Object obj = get(key);
		return ObjectUtil.isEmpty(obj) ? null : (T) obj;
	}

	public static void set(Map<String, Object> valueMap) {
		Map<String, Object> localMap = threadLocal.get();
		if (localMap == null) {
			localMap = new HashMap<String, Object>();
			threadLocal.set(localMap);
		}
		localMap.putAll(valueMap);
	}

	public static void remove() {
		threadLocal.remove();
	}

}
